package com.delicious.servlet;

import java.io.File;
import java.io.IOException;
import java.util.List;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.delicious.dao.impl.FoodsDaoImpl;
import com.delicious.entity.Foods;

public class FoodsManagerServlet extends HttpServlet {

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		//创建diskFileItemFactory
		FileItemFactory factory = new DiskFileItemFactory();
		//创建ServletFileUpload对象
		ServletFileUpload upload = new ServletFileUpload(factory);
		
		String filename = null ;
		String englishName = null;
		String chineseName = null;
		String description = null;
		int id = 0;
		String path = null;
		int cid = 0 ;
		try {
			List<FileItem> items = upload.parseRequest(request);
			for(FileItem item : items){
				if(item.isFormField()){//是否为表格
					if("english".equals(item.getFieldName()))
						englishName = item.getString("UTF-8");
					if("chinese".equals(item.getFieldName()))
						chineseName = item.getString("UTF-8");
					if("foodDesc".equals(item.getFieldName()))
						description = item.getString("UTF-8");
					if("cid".equals(item.getFieldName()))
						cid = Integer.parseInt(item.getString("UTF-8"));
				}else{
					//获取原来上传的文件名
					String client= item.getName();
					//更改文件名，避免重复
					filename = englishName + client.substring(client.lastIndexOf("."));
					ServletContext application = request.getSession().getServletContext();
					path = application.getRealPath("/images/menus/"+filename);
					item.write(new File(path));
				}
				
			}
			Foods food = new Foods(id, chineseName, englishName, cid, description);
			if(new FoodsDaoImpl().checkFoods(chineseName)){
				if(new FoodsDaoImpl().updateDate(food)){
					request.getSession().setAttribute("state", "修改成功");
				}
				else{
					request.getSession().setAttribute("state", "修改失败");
				}
			}else{
				if(new FoodsDaoImpl().updateDate(food)){
					request.getSession().setAttribute("state", "添加成功");
				}
				else{
					request.getSession().setAttribute("state", "添加失败");
				}
			}
			response.sendRedirect("GetFoodsServlet");

			} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}

}
